package com.homegoods.login.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.ArrayMap;
import android.widget.ArrayAdapter;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.homegoods.login.KGetVerHelper;
import com.homegoods.login.R;
import com.homegoods.login.databinding.LoginSmsActivityBindingImpl;
import com.homegoods.login.evnet.LoginSucEvent;
import com.homegoods.login.presenter.LoginSmsPresenter;
import com.homegoods.login.view.LoginSmsView;
import com.homegoods.aroutercomment.ARouterPath;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.kedll.library.base.MyBaseFragmentActivity;
import com.kedll.library.dialog.ECAlertDialog;
import com.kedll.library.util.KeyBoardUtils;
import com.kedll.library.util.MyLog;
import com.kedll.library.util.MyUtils;
import com.kedll.library.util.RxBus;
import com.kedll.library.util.StringUtil;
import com.kedll.library.util.ToastUtil;
import com.kedll.library.widget.AIAutoCompleteTextView;
import com.share.sharelibrary.ThirdLoginView;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;
import java.util.Objects;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * @author QiQi
 * @ClassName: LoginActivity
 * @date 2018/9/12
 * @description 短信快捷登录
 *
 * shibo.zheng
 * ***************废弃****************
 */
@RuntimePermissions
@Route(path = ARouterPath.PATH_LOGIN_SMS)
public class LoginWithSmsActivity extends MyBaseFragmentActivity<LoginSmsActivityBindingImpl, LoginSmsPresenter> implements LoginSmsView {

    private AIAutoCompleteTextView mPhone;
    private KGetVerHelper kGetVerHelper;
    private ThirdLoginView thirdLoginView;

    @Override
    protected int getLayout() {
        return R.layout.login_sms_activity;
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initEvent() {
        LoginWithSmsActivityPermissionsDispatcher.requestUMWithPermissionCheck(this);
        RxBus.getDefault().toFlowable(LoginSucEvent.class)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(loginSucEvent -> {
                    ToastUtil.showToast(R.string.login_suc);
                    ARouter.getInstance().build(ARouterPath.PATH_MAIN_HOME).navigation();
                    finish();
                });
        RxTextView.afterTextChangeEvents(mBinding.inputVer)
                .compose(bindToLifecycle())
                .subscribe(textChangeEvent -> mBinding.btnLogin.setEnabled(Objects.requireNonNull(textChangeEvent.editable()).length() > 0
                        && StringUtil.isNotEmpty(mPhone.getText())));

        RxTextView.afterTextChangeEvents(mBinding.phone)
                .compose(bindToLifecycle())
                .subscribe(textChangeEvent -> mBinding.btnLogin.setEnabled(
                        Objects.requireNonNull(textChangeEvent.editable()).length() > 0
                                && StringUtil.isNotEmpty(mBinding.inputVer.getText())));

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LoginWithSmsActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public void showLoad(String msg) {
        MyLog.getInstance().showProgressDialog(this, msg);
    }

    @Override
    public void hideLoad() {
        MyLog.getInstance().dismissDialog();
    }

    @Override
    public Context getContext() {
        return getApplicationContext();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);

//        mPresenter.initAutoComplete(this); TODO
        mBinding.setLogin(mPresenter);
        mPhone = mBinding.phone;

        mBinding.userAgreement.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        mBinding.userAgreement.getPaint().setAntiAlias(true);//抗锯齿

        toolbar.setNavigationIcon(R.drawable.login_ic_close);
        toolbar.setNavigationOnClickListener(v -> {
            ARouter.getInstance().build(ARouterPath.PATH_MAIN_HOME).navigation();
            finish();

        });
        thirdLoginView = mBinding.thirdLogin;

        thirdLoginView.setColumnNum(2);
        thirdLoginView.hideHeadView();

        Map<SHARE_MEDIA, Integer> map = new ArrayMap<>();
        map.put(SHARE_MEDIA.WEIXIN, R.mipmap.wechat_login);
        map.put(SHARE_MEDIA.QQ, R.mipmap.qq_login);

        thirdLoginView.setPlatForm(map, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.QQ);
        //QQ登录
        thirdLoginView.setLogin(access_token ->
                mPresenter.qqLogin(access_token));
    }

    @Override
    protected LoginSmsPresenter getPresenter() {
        kGetVerHelper = new KGetVerHelper(this, mBinding.getVer);
        return /*new LoginSmsPresenter(kGetVerHelper, this)*/null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (kGetVerHelper != null) {
            kGetVerHelper.restart();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (kGetVerHelper != null) {
            kGetVerHelper.cancel();
            kGetVerHelper = null;
        }
    }

    private boolean isFromActivityReCreate = false; // 执行onCretae是否是带有savedInstanceState启动的

    @Override
    protected void onPause() {
        super.onPause();
        if (kGetVerHelper != null) {
            kGetVerHelper.stop();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        MyUtils.setSystemUi(getWindow(), false);
    }

    @Override
    protected void onStop() {
        super.onStop();
        MyUtils.setSystemUi(getWindow(), true);
    }

    /**
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == RESULT_CANCELED || data == null) {
                return;
            }

            String phoneNum = data.getStringExtra("phoneNum");
            mPhone.setText(phoneNum);
            mPhone.setSelection(phoneNum.length());

        } else {
            thirdLoginView.onResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void hideKeyBoard() {
        KeyBoardUtils.hideKeyBoard(this);
    }

    @Override
    public void showLoginView() {
        ARouter.getInstance()
                .build(ARouterPath.PATH_LOGIN)
                .navigation(this, 100);
    }

    @Override
    public void haveNoVercorde() {
        ECAlertDialog dialog = ECAlertDialog.buildAlert(
                this,
                "如若您的手机号收不到短信验证码请致电" +
                        "客服，客服热线400-83-213423"
                , "取消"
                , "拨打"
                , null
                , (dialog1, which) -> {
                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:400-83-213423"));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
        );
        dialog.show();
    }

    @Override
    public void setAutoTextViewAdapter(ArrayAdapter adapter) {
//        if (adapter != null)
////            mPhone.setAdapter(adapter);
    }

    @NeedsPermission({Manifest.permission.READ_CALENDAR, Manifest.permission.GET_ACCOUNTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void requestUM() {
    }
}
